#include <WiFi.h>
#define BLINKER_WIFI
#include <Blinker.h>
#include <HardwareSerial.h>
#include "oled.h"
#include <esp_wifi.h>

char auth[] = "49689996987e";
//char auth[] = "8c4a96aac48b";
// char sid[] = "dnn";
// char pwd[] = "15864312056";
uint8_t Save_Data[15]={0};
uint8_t length = 0;
hw_timer_t *timer = NULL;            //声明一个定时器

uint8_t wifi = 1,blinker_ok = 0,uartinit = 1;

BlinkerButton Button1("btn-abc");
BlinkerNumber TEMP("temp-a");//温度
BlinkerNumber HUM("hum-a");//湿度
BlinkerNumber LX("lx-a");//光照
BlinkerNumber CONT("cont-a");//浓度

uint16_t Temp,Hum,Illi,concentration;

void func(const char *str) {
  OLED_ShowString(30,0,"                 ",12, 1);
  OLED_Refresh();
  OLED_ShowString(30,0,str,12, 1);
  OLED_Refresh();
 }

void show_data(uint16_t temp,uint16_t hum){
  OLED_ShowString(0,15,"Temp:",12, 1);
  OLED_ShowNum(30,15,temp,3,12, 1);
  OLED_ShowString(55,15,"'C",12, 1);
  OLED_ShowString(0,25,"Hum:",12, 1);
  OLED_ShowNum(30,25,hum,3,12, 1);
  OLED_ShowString(55,25,"%RH",12, 1);
  OLED_ShowString(0,35,"Illi:",12, 1);
  OLED_ShowNum(30,35,Illi,4,12, 1);
  OLED_ShowString(60,35,"Lx",12, 1);
  OLED_ShowString(0,45,"Cont:",12, 1);
  OLED_ShowNum(30,45,concentration,3,12, 1);
  OLED_ShowString(55,45,"%",12, 1);
  OLED_Refresh();
}
//连接WIFI
void SmartConfig()
{
  OLED_Clear();
  OLED_ShowString(0,0,"wifi:",12, 1);
  OLED_ShowString(30,0,"                 ",12, 1);
  OLED_Refresh();
  OLED_ShowString(30,0,"Wait Config....",12, 1);
  OLED_Refresh();
  WiFi.mode(WIFI_STA);
  Serial.println("\r\nWait for Smartconfig...");
  WiFi.beginSmartConfig();
  while (1)
  {
    Serial.print(".");
    delay(500); 
    // if (digitalRead(15) == 0)
    // {
    //   /* code */
    //   wifi = 0;
    //   WiFi.stopSmartConfig();
    //   OLED_ShowString(30,0,"                 ",12, 1);
    //   OLED_ShowString(30,0,"N/A",12, 1);
    //   OLED_Refresh();
    //   Serial2.begin(115200);
    //   blinker_ok = 1;
    //   break;
    // }
    
    if (WiFi.smartConfigDone())
    {
      Serial.println("\r\nSmartConfig Success");
      Serial.printf("SSID:%s\r\n", WiFi.SSID().c_str());
      Serial.printf("PSW:%s\r\n", WiFi.psk().c_str());
      func(WiFi.SSID().c_str());
      Blinker.begin(auth, WiFi.SSID().c_str(), WiFi.psk().c_str());
      // WiFi.stopSmartConfig();
      break;
    }
  }
}

//自动重连
bool AutoConfig()
{
    OLED_Clear();
    OLED_ShowString(0,0,"wifi:",12, 1);
    OLED_ShowString(30,0,"Auto Config....",12, 1);
    OLED_Refresh();
    WiFi.begin();
    //如果觉得时间太长可改
    for (int i = 0; i < 20; i++)
    {
        int wstatus = WiFi.status();
        // if (digitalRead(15) == 0)
        // {
        //   /* code */
        //   wifi = 0;
        //   OLED_ShowString(30,0,"                 ",12, 1);
        //   OLED_ShowString(30,0,"N/A",12, 1);
        //   OLED_Refresh();
        //   Serial2.begin(115200);
        //   blinker_ok = 1;
        //   return true;
        // }
        if (wstatus == WL_CONNECTED)
        {
	        Serial.println("WIFI SmartConfig Success");
	        Serial.printf("SSID:%s", WiFi.SSID().c_str());
	        Serial.printf(", PSW:%s\r\n", WiFi.psk().c_str());
	        Serial.print("LocalIP:");
	        Serial.print(WiFi.localIP());
	        Serial.print(" ,GateIP:");
	        Serial.println(WiFi.gatewayIP());
          func(WiFi.SSID().c_str());
          Blinker.begin(auth, WiFi.SSID().c_str(), WiFi.psk().c_str());
	        return true;
        }
        else
        {
	        Serial.print("WIFI AutoConfig Waiting......");
	        Serial.println(wstatus);
	        delay(1000);
        }
        
    }
    Serial.println("WIFI AutoConfig Faild!" );
    return false;
}


void button1_callback(const String & state) {
    BLINKER_LOG("get button state: ", state);
    digitalWrite(2, !digitalRead(2));
}
 
void heartbeat(){
  TEMP.print(Temp);
  HUM.print(Hum);
  LX.print(Illi);
  CONT.print(concentration);
}

void IRAM_ATTR onTimer(){
  
}

void setup() {
    // 初始化串口
    Serial.begin(115200);
    // Serial2.begin(115200);
    OLED_Init();
    OLED_ShowString(0,0,"wifi:",12, 1);
    OLED_ShowString(30,0,"Wait Config....",12, 1);
    OLED_Refresh();
    pinMode(13, INPUT_PULLUP);
    pinMode(15, INPUT_PULLUP);
    delay(100);

    if (digitalRead(15) == 0)//不开wifi
    {
      /* code */
      wifi = 0;
      OLED_ShowString(30,0,"                 ",12, 1);
      OLED_ShowString(30,0,"N/A",12, 1);
      OLED_Refresh();
      Serial2.begin(115200);
      blinker_ok = 1;
    }
    else{//开wifi
      if(digitalRead(13) == 0){//需要重连
        SmartConfig();
      }
      else{//不要重连
        if (!AutoConfig())
        {
  	      SmartConfig();
        }
      }
      
    }
    
    
    // 初始化blinker
    // Blinker.begin(auth, sid, pwd);
    if(wifi==1){
      pinMode(2, OUTPUT);
      digitalWrite(2, HIGH);
      Button1.attach(button1_callback);
      Blinker.attachHeartbeat(heartbeat);
      BLINKER_DEBUG.stream(Serial);
    }
    
    // timer = timerBegin(0, 79, true);                //初始化
    // timerAttachInterrupt(timer, &onTimer, true);    //调用中断函数
    // timerAlarmWrite(timer, 1000000, true);        //timerBegin的参数二 80位80MHZ，这里为1000000  意思为1秒
    // timerAlarmEnable(timer);                //定时器使能
}
 
void loop() {
   Blinker.run();
  //  if(digitalRead(13)==0){
  //   // WiFi.disconnect();
  //   // esp_wifi_restore();
  //   Serial1.end();
  //   SmartConfig();
  //   Button1.attach(button1_callback);
  //   Blinker.attachHeartbeat(heartbeat);
  //   uartinit = 1;
  //   blinker_ok = 0;
  //  }
   if (Blinker.connected()==1 && uartinit == 1){
    uartinit = 0;
    Serial2.begin(115200);
    blinker_ok = 1;
   }
   if (Serial2.available() && blinker_ok == 1) { 
      length = 0;
      while (Serial2.available()) {
        Save_Data[length] = Serial2.read();         
        length++;
        // if (receivedByte < 0x10) {
        //   Serial.print("0");
        // }
        
        // Serial.print(" ");
      }
      Temp = Save_Data[1];
      Hum = Save_Data[2];
      Illi = (Save_Data[3]<<8)|Save_Data[4];
      concentration = Save_Data[5];
      Serial.printf("data:%d %d %d %d",Temp,Hum,Illi,concentration);
      Serial.println();
   }
   if (Save_Data[0] == 0x5A && Save_Data[6] == 0xA5/* condition */)
   {
     show_data(Temp,Hum);
   } else {
      OLED_ShowString(0,15,"Temp:",12, 1);
      OLED_ShowString(55,15,"'C",12, 1);
      OLED_ShowString(0,25,"Hum:",12, 1);
      OLED_ShowString(55,25,"%RH",12, 1);
      OLED_ShowString(0,35,"Illi:",12, 1);
      OLED_ShowString(60,35,"Lx",12, 1);
      OLED_ShowString(0,45,"Cont:",12, 1);
      OLED_ShowString(55,45,"%",12, 1);
      OLED_Refresh();
   }
  //  Serial.printf("connect:%d", Blinker.connected());
  //  Serial.println();
}


